/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sui.bigdata.flink.sql.side.rdb.async;

import com.sui.bigdata.flink.sql.core.side.*;
import com.sui.bigdata.flink.sql.side.rdb.table.RdbSideTableInfo;
import com.sui.bigdata.flink.sql.core.side.*;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.shaded.guava18.com.google.common.collect.Lists;

import java.util.List;
import java.util.Map;

import static org.apache.calcite.sql.SqlKind.*;

/**
 * Reason:
 * Date: 2018/11/26
 * Company: www.dtstack.com
 *
 * @author maqi
 */

public class RdbAsyncSideInfo extends SideInfo {

    private static final long serialVersionUID = 1942629132469918611L;


    public RdbAsyncSideInfo(RowTypeInfo rowTypeInfo, JoinInfo joinInfo, List<FieldInfo> outFieldInfoList, SideTableInfo sideTableInfo) {
        super(rowTypeInfo, joinInfo, outFieldInfoList, sideTableInfo);
    }

    @Override
    public void buildEqualInfo(JoinInfo joinInfo, SideTableInfo sideTableInfo, Map<Integer,String> sideFieldNameIndex,Map<Integer,String> inFieldNameIndex) {
        RdbSideTableInfo rdbSideTableInfo = (RdbSideTableInfo) sideTableInfo;

        String sideTableName = joinInfo.getSideTableName();

        SqlNode conditionNode = joinInfo.getCondition();

        List<SqlNode> sqlNodeList = Lists.newArrayList();
        if (conditionNode.getKind() == SqlKind.AND) {
            SqlNode leftConditionNode = conditionNode;
            SqlNode rightConditionNode = null;
            do {
                rightConditionNode = ((SqlBasicCall) leftConditionNode).getOperands()[1];
                leftConditionNode = ((SqlBasicCall) leftConditionNode).getOperands()[0];
                sqlNodeList.add(rightConditionNode);
            } while (leftConditionNode.getKind() != SqlKind.EQUALS);
            sqlNodeList.add(leftConditionNode);
        } else {
            sqlNodeList.add(conditionNode);
        }

        for(SqlNode sqlNode : sqlNodeList){
            dealEqualCon(sqlNode, sideTableName,sideFieldNameIndex,inFieldNameIndex);
        }
        sqlCondition = "select ${selectField} from ${tableName} where ";

        for (int i = 0; i < joinCondition.size(); i++) {
            String oneCondition = joinCondition.get(i);
            sqlCondition +=   oneCondition + " and ";
        }

        for (int i = 0; i < equalFieldList.size(); i++) {
            String equalField = equalFieldList.get(i);

            sqlCondition += equalField + "=? ";
            if (i != equalFieldList.size() - 1) {
                sqlCondition += " and ";
            }
        }


        sqlCondition = sqlCondition.replace("${tableName}", rdbSideTableInfo.getTableName()).replace("${selectField}", sideSelectFields);
        System.out.println("---------side_exe_sql-----\n" + sqlCondition);
    }


    @Override
    public void dealEqualCon(SqlNode sqlNode, String sideTableName, Map<Integer,String> sideFieldNameIndex,Map<Integer,String> inFieldNameIndex) {
        if (sqlNode.getKind() != SqlKind.EQUALS &&
                sqlNode.getKind() != NOT_EQUALS &&
                sqlNode.getKind() != GREATER_THAN &&
                sqlNode.getKind() != GREATER_THAN_OR_EQUAL &&
                sqlNode.getKind() != LESS_THAN &&
                sqlNode.getKind() != LESS_THAN_OR_EQUAL) {
            throw new RuntimeException(" on condition not support " + sqlNode.getKind() + " operator.");
        }

        SqlIdentifier left = (SqlIdentifier) ((SqlBasicCall) sqlNode).getOperands()[0];
        SqlIdentifier right = null;
        try {
            right = (SqlIdentifier) ((SqlBasicCall) sqlNode).getOperands()[1];
        } catch (Exception e) {
            JoinFilterInfo joinFilterInfo = new JoinFilterInfo();
            SqlKind operate = sqlNode.getKind();
            String rightStr = ((SqlBasicCall) sqlNode).getOperands()[1].toString();
            for(Map.Entry<Integer,String> mapEntry: sideFieldNameIndex.entrySet() ){
                if (left.getComponent(1).getSimple().equals(mapEntry.getValue())){
                    String oneCondition = "";
                    oneCondition += left.getComponent(1).getSimple();
                    oneCondition += " "+operate.sql;
                    oneCondition += " "+rightStr;
                    joinCondition.add(oneCondition);
                }
            }
            String leftTableName = left.getComponent(0).getSimple();
            String leftField = left.getComponent(1).getSimple();
            if (!leftTableName.equals(sideTableName)){
                for (Map.Entry<Integer, String> mapEntry : inFieldNameIndex.entrySet()) {
                    if (leftField.equals(mapEntry.getValue())) {
                        joinFilterInfo.setOperate(operate);
                        joinFilterInfo.setLeftFieldIndex(mapEntry.getKey());
                        joinFilterInfo.setRightConstant(rightStr.replace("'", ""));
                        joinFilterInfos.add(joinFilterInfo);
                    }
                }
            }
            return;
        }
        String leftTableName = left.getComponent(0).getSimple();
        String leftField = left.getComponent(1).getSimple();

        String rightTableName = right.getComponent(0).getSimple();
        String rightField = right.getComponent(1).getSimple();

        if (leftTableName.equalsIgnoreCase(sideTableName)) {
            equalFieldList.add(leftField);
            int equalFieldIndex = -1;
            for (int i = 0; i < rowTypeInfo.getFieldNames().length; i++) {
                String fieldName = rowTypeInfo.getFieldNames()[i];
                if (fieldName.equalsIgnoreCase(rightField)) {
                    equalFieldIndex = i;
                }
            }
            if (equalFieldIndex == -1) {
                throw new RuntimeException("can't deal equal field: " + sqlNode);
            }

            equalValIndex.add(equalFieldIndex);

        } else if (rightTableName.equalsIgnoreCase(sideTableName)) {

            equalFieldList.add(rightField);
            int equalFieldIndex = -1;
            for (int i = 0; i < rowTypeInfo.getFieldNames().length; i++) {
                String fieldName = rowTypeInfo.getFieldNames()[i];
                if (fieldName.equalsIgnoreCase(leftField)) {
                    equalFieldIndex = i;
                }
            }
            if (equalFieldIndex == -1) {
                throw new RuntimeException("can't deal equal field: " + sqlNode.toString());
            }

            equalValIndex.add(equalFieldIndex);

        } else {
            throw new RuntimeException("resolve equalFieldList error:" + sqlNode.toString());
        }

    }

}
